package com.younion.common.paginator;

import javax.servlet.http.HttpServletRequest;

import com.younion.common.system.SystemConfig;

/**
 * 分页工具类，根据页面request定义分页对象
 * 
 * @author wwz
 */

public abstract class PaginatorUtil {
	public PaginatorUtil() {

	}

	public static Paginator getPaginator(HttpServletRequest request) {
		final SystemConfig sm = SystemConfig.getInstance();
		String ps = sm.getPropValue("pageSize");
		Paginator paginator = new Paginator();
		if (ps == null || "".equals(ps)) {
			ps = String.valueOf(paginator.getPageSize());
		}
		String pageRequest = request.getParameter("pageRequest");
		if ("1".equals(pageRequest)) {
			String pageSize = getParameterWithDefault(request, "numPerPage", ps);
			paginator.setPageSize(Integer.parseInt(pageSize));
			String pageIndex = getParameterWithDefault(request, "pageNum", "1");
			paginator.setPageIndex(Integer.parseInt(pageIndex));
		} else {
			paginator.setPageSize(Integer.valueOf(ps));
			paginator.setPageIndex(1);
		}
		return paginator;
	}

	public static String getParameterWithDefault(HttpServletRequest request, String name,
			String defaultValue) {
		String paramValue = request.getParameter(name);

		if (paramValue == null || "".equals(paramValue) || "0".equals(paramValue)) {
			paramValue = defaultValue;
		}
		return paramValue;
	}

}
